#!/usr/bin/env bash

# This is a Bash script that checks links in Markdown files within a subfolder.

set -Eeuo pipefail
shopt -s inherit_errexit

# shellcheck source-path=SCRIPTDIR
. cki_utils.sh

# Check for an argument
if [[ $# -ne 1 ]]; then
  cki_echo_red "Usage: $0 checked_file"
  exit 1
fi

checked_file="$1"

# Check if the `checked_file` exists
if [[ ! -f "${checked_file}" ]]; then
  cki_echo_red "Error: ${checked_file} does not exist or is not a regular file"
  exit 1
fi

# Find the check-links files and store them in an array
files=(check-links-*.txt)

# If any files were found, concatenate their contents with commas
if [[ -f "${files[0]}" ]]; then
  excludes=$(cat "${files[@]}" | tr '\n' ',')
else
  excludes=""
fi

# Run the checker
urlchecker check "${checked_file}" \
    --exclude-pattern "${excludes}" \
    --timeout 30 \
    --retry-count 3 \
    --no-print \
    --force-pass
